package com.action.ui.fragment;

import android.content.Intent;
import android.graphics.Paint;
import android.view.View;
import android.widget.TextView;

import com.action.childbase.ChildBaseFragment;
import com.action.entity.event.WxLoginEvent;
import com.action.service.pressenter.EntryPressenter;
import com.action.ui.activity.XYBMainActiviy;
import com.action.ui.activity.RegisterRuleActivity;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.base.app_core.App;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.user.model.User;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.BeanPropertiesUtil;
import com.base.app_core.util.MaterialDialogHelper;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.StringUtils;
import com.hwangjr.rxbus.Bus;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.xinglai.yun.R;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


public class EntryFragment extends ChildBaseFragment<EntryPressenter> implements ActionPacketView.LoginView {

    @BindView(R.id.text2)
    TextView registerHint;
    @Inject
    User user;

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void consumeWxLoginEvent(WxLoginEvent wxLoginEvent) {
        dismissProgress();
        int errorCode = wxLoginEvent.getErrorCode();
        if (errorCode == 0) {
            showProgress();
            mPresenter.wxLogin(wxLoginEvent.getCode());
        } else if (errorCode == -2) {
            MaterialDialogHelper.showSingleText(getActivity(), "快登录微信赚大钱吧!", "取消",
                    "重新授权", new MaterialDialogHelper.onItemClickLisener() {
                        @Override
                        public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                            requestWxLogin();
                            dialog.dismiss();
                        }

                        @Override
                        public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                            dismissProgress();
                        }
                    });
        } else {
            MaterialDialogHelper.showSingleText(getActivity(), "微信登录遇到问题?", "取消",
                    "重新授权", new MaterialDialogHelper.onItemClickLisener() {
                        @Override
                        public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                            requestWxLogin();
                            dialog.dismiss();
                        }

                        @Override
                        public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                            dismissProgress();
                        }
                    });
        }
    }

    @Override
    protected void initView() {
        super.initView();
        App.getApp().regToWx();
        String token = Preferences.getDefault().getString(AppConstants.SP.JWTOKEN, null);
        String mobile = Preferences.getDefault().getString(AppConstants.SP.MOBILE, null);
        if (StringUtils.isEmpty(token)) {
            RxBus.get().register(this);
        } else {
            startActivity(new Intent(getActivity(), XYBMainActiviy.class));
            getActivity().finish();
        }
        registerHint.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_entry;
    }

    @Override
    protected boolean isNeedShowLoading() {
        return false;
    }

    @OnClick({R.id.btn_entry, R.id.ll_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_entry:
                Preferences.putBoolean(AppConstants.SP.IS_FIRST, false);
                requestWxLogin();
                break;
            case R.id.ll_register:
                startActivity(new Intent(getActivity(), RegisterRuleActivity.class));
                break;
        }
    }

    private void requestWxLogin() {
        if (XYBAUtils.checkApkExist(getActivity())) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            IWXAPI iwxapi = App.getApp().iwxapi;
            if (iwxapi == null) {
                return;
            }
            boolean result = iwxapi.sendReq(req);
            if (result) {
                showProgress();
            } else {
                showToast("微信调用失败,请检查网络环境");
            }
            F.j(result + "");
        } else {
            showToast("请安装微信");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Bus bus = RxBus.get();
        if (bus.hasRegistered(this)) {
            bus.unregister(this);
        }
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }


    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        dismissProgress();

        if (object instanceof User) {
            showToast("登录成功");
            try {
                BeanPropertiesUtil.copyProperties(object, user);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (user.getLat() != null && user.getLng() != null) {
                Preferences.putString(AppConstants.SP.LAT, String.valueOf(user.getLat()));
                Preferences.putString(AppConstants.SP.LNG, String.valueOf(user.getLng()));
                Preferences.putLong(AppConstants.SP.RANGE, user.getRange());
            }
            startActivity(new Intent(getActivity(), XYBMainActiviy.class));
            getActivity().finish();
        }
    }

    @Override
    public void notifyError(String errorCode, String content) {
        super.notifyError(errorCode, content);
    }
}
